<?php


namespace app\index\controller;


use app\index\validate\UserValidator;
use think\Controller;
use think\Db;
use think\Request;
use app\index\model\User as UserModel;

class User extends Controller
{
    public function login()
    {
        return $this->fetch();
    }

    public function do_login(Request $request)
    {
        $username = $request->param("username");
        $password = $request->param("password");
//        echo $username;
//        echo $password;
        $result = Db::table("mb_user")
            ->where("username", $username)
            ->where("password", $password)
            ->select();
        if ($result) {
            session("username", $username);
            session("user_id", $result[0]["user_id"]);
            $this->success("登录成功", "index/index");
        } else {
            $this->error("登录失败", "login");
        }
    }

    public function register()
    {
        return $this->fetch();

    }

    public function do_reg(Request $request)
    {
        $datas = $request->param();
        $a  = Db::query("select username from mb_user where username = '" . $datas['username'] . "'");
        if($a){
            foreach ($a as $item){
                $dbname = $item["username"];
            }
        }
        else
            $dbname = "";
        $datas['dbname']=$dbname;
        $vali = new UserValidator();//构造自定义的验证器类实例，其中定义了$sence
        if(!$vali->scene('edit')->check($datas))
            return $vali->getError();
        else{
        $user = new UserModel();
        if ($user->allowField(true)->save($datas))
            $this->success("注册成功", "login");
        else
            $this->error("注册失败", "register");}

    }

    public function change_pwd()
    {

        return $this->fetch();
    }
    public function do_change_pwd(Request $request)
    {
        $datas = $request->param();
        $username = $request->param("username");
        $newpwd = $request->param("password");


        $vali = new UserValidator();//构造自定义的验证器类实例，其中定义了$sence
        if(!$vali->scene('edit')->check($datas))
            return $vali->getError();
        else {
            $result = Db::table("mb_user")
                ->where('username', $username)
                ->update(["password" => $newpwd]);

            if ($result)
                $this->success("修改密码成功", "index/index");
            else
                $this->error("修改密码失败", "change_pwd");
        }

    }
    public function logout()
    {
        session(null);
        $this->redirect('index/index');
    }
}